package com.tju.ocean_ecology_website.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Arrays;
import java.util.List;

/**
 * 文件上传配置类
 */
@Configuration
public class FileUploadConfig implements WebMvcConfigurer {

    // 上传根目录
    @Value("${file.upload.root-dir:uploads}")
    private String uploadRootDir;

    // 文件访问基础URL
    @Value("${file.upload.base-url:}")
    private String baseUrl;

    // 最大文件大小（默认2MB）
    @Value("${file.upload.max-size:2097152}")
    private long maxFileSize;

    // 允许的图片类型
    private static final List<String> ALLOWED_IMAGE_TYPES = Arrays.asList(
            "image/jpeg", "image/png", "image/gif", "image/webp", "image/bmp"
    );

    /**
     * 获取允许的图片类型
     */
    public List<String> getAllowedImageTypes() {
        return ALLOWED_IMAGE_TYPES;
    }

    /**
     * 获取最大文件大小
     */
    public long getMaxFileSize() {
        return maxFileSize;
    }

    /**
     * 获取上传根目录
     */
    public String getUploadRootDir() {
        return uploadRootDir;
    }

    /**
     * 获取文件访问基础URL
     */
    public String getBaseUrl() {
        return baseUrl;
    }

    /**
     * 配置静态资源处理器
     * 使上传的文件可以通过URL访问
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/" + uploadRootDir + "/**")
                .addResourceLocations("file:./" + uploadRootDir + "/");
    }

    /**
     * 配置Multipart解析器
     */
    @Bean
    public MultipartResolver multipartResolver() {
        return new StandardServletMultipartResolver();
    }
}
